/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.service.GoodsService;

/**
 * 物料Controller
 * @author 李超辉
 * @version 2017-12-14
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/goods")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ProjectService projectService;
	
	@ModelAttribute
	public Goods get(@RequestParam(required=false) String id) {
		Goods entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = goodsService.get(id);
		}
		if (entity == null){
			entity = new Goods();
		}
		return entity;
	}
	
	/**
	 * 物料列表页面
	 */
	@RequiresPermissions("infor:goods:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/goodsList";
	}
	
		/**
	 * 物料列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:goods:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Goods goods, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
				goods.setProject(pro);
		}
		if(goods.getName()!=null &goods.getName()!=""){
			String name=goods.getName();
			String a="";
			String b="";
			String c="";
			String d="";
			String e="";
			String f="";
			String g="";
			String n="";
			boolean bol=true;
			if(bol){
				if(name.indexOf("\\")>=0){
					a=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					b=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					c=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+b+"\\\\"+name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					d=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+b+"\\\\"+c+"\\\\"+name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					e=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					f=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+e+"\\\\"+name;
					bol=false;
				}}
			if(bol){
				if(name.indexOf("\\")>=0){
					g=name.substring(0,name.indexOf("\\"));
					name=name.substring(name.indexOf("\\")+1);
				}else{
					n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+e+"\\\\"+f+"\\\\"+name;
				}}

			goods.setName(n);
		}
		Page<Goods> page = goodsService.findPage(new Page<Goods>(request, response), goods);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑物料表单页面
	 */
	@RequiresPermissions(value={"infor:goods:view","infor:goods:add","infor:goods:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Goods goods, Model model) {
		if(goods.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				goods.setProject(pro);
			}
		}
		model.addAttribute("goods", goods);
		return "modules/infor/goodsForm";
	}
@ResponseBody
@RequestMapping("getGoodsByName")
public String getGoodsByName(String name){
		Goods goods=new Goods();
	String pro= UserUtils.getUseroffice();
	if(!pro.equals("总部")){
		goods.setProject(pro);
	}
		String a="";
		String b="";
		String c="";
		String d="";
		String e="";
		String f="";
		String g="";
		String n="";
		boolean bol=true;
		if(bol){
			if(name.indexOf("\\")>=0){
				a=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				b=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				c=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+b+"\\\\"+name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				d=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+b+"\\\\"+c+"\\\\"+name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				e=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				f=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+e+"\\\\"+name;
				bol=false;
			}}
		if(bol){
			if(name.indexOf("\\")>=0){
				g=name.substring(0,name.indexOf("\\"));
				name=name.substring(name.indexOf("\\")+1);
			}else{
				n=a+"\\\\"+b+"\\\\"+c+"\\\\"+d+"\\\\"+e+"\\\\"+f+"\\\\"+name;
			}}
		goods.setName(n);
		List<Goods> l=goodsService.findList(goods);
	Gson gson=new Gson();
		return gson.toJson(l).toString();
}
	@ResponseBody
	@RequestMapping("getGoodsByCode")
	public String getGoodsByCode(String code){
		Goods g=new Goods();
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			g.setProject(pro);
		}
		g.setCode(code);
		List<Goods> l=goodsService.findList(g);
		Gson gson=new Gson();
		return gson.toJson(l).toString();
	}

@RequestMapping("getById")
@ResponseBody
public Goods getById(String i){
	return  goodsService.get(i);
}

	/**
	 * 保存物料
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:goods:add","infor:goods:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Goods goods, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, goods)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		goodsService.save(goods);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存物料成功");
		return j;
	}
	
	/**
	 * 删除物料
	 */
	@ResponseBody
	@RequiresPermissions("infor:goods:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Goods goods, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		goodsService.delete(goods);
		j.setMsg("删除物料成功");
		return j;
	}
	
	/**
	 * 批量删除物料
	 */
	@ResponseBody
	@RequiresPermissions("infor:goods:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			goodsService.delete(goodsService.get(id));
		}
		j.setMsg("删除物料成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("infor:goods:export")
    @RequestMapping(value = "export")
    public String exportFile(Goods goods, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

		try {
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				goods.setProject(pro);
			}
            String fileName = "物料"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Goods> page = goodsService.findPage(new Page<Goods>(request, response, -1), goods);
    		new ExportExcel("物料", Goods.class).setDataList(page.getList()).write(response, fileName).dispose();

    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物料失败！失败信息："+e.getMessage());

		}
		return "redirect:" + adminPath + "/infor/goods/list?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:goods:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Goods> list = ei.getDataList(Goods.class);
			for (Goods goods : list){
				try{String pro= UserUtils.getUseroffice();
					if(!pro.equals("总部")){
						goods.setProject(pro);
					}
					goods.setMoney("1");
					goodsService.save(goods);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条物料记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条物料记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入物料失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/goods/?repage";
    }
	
	/**
	 * 下载导入物料数据模板
	 */
	@RequiresPermissions("infor:goods:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物料数据导入模板.xlsx";
    		List<Goods> list = Lists.newArrayList(); 
    		new ExportExcel("物料数据", Goods.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/goods/?repage";
    }

}